package com.mxy.screenlock;

import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

/**
 * 一键锁屏功能Activity
 *
 * @author 马晓勇
 */
public class MainActivity extends Activity {

    private ComponentName componentName = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        componentName = new ComponentName(this, AdminManageReceiver.class);
        //在设备上执行管理政策
        DevicePolicyManager devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        //如果未激活
        if (!devicePolicyManager.isAdminActive(componentName)) {
            //打开手机设备管理器
            showAdminManagement();
        } else {
            //执行锁屏
            devicePolicyManager.lockNow();
        }
        finish();
        //直接结束进程，避免在任务中保存app
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    private void showAdminManagement() {
        //打开手机设备管理器的intent
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "请授予“一键锁屏”应用设备管理权限");
        startActivity(intent);
    }
}